package com.simon.jkxj.ui.home;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.simon.jkxj.R;
import com.simon.jkxj.adapter.PostAdapter;
import com.simon.jkxj.model.Post;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Random;

public class DiscoveryFragment extends Fragment {
    private static final String TAG = "DiscoveryFragment";
    
    private ViewPager2 bannerViewPager;
    private LinearLayout indicatorContainer;
    
    // 轮播图自动滚动
    private Timer bannerTimer;
    private int currentBannerPosition = 0;
    private final int BANNER_COUNT = 3; // 轮播图数量
    private Handler handler;

    private RecyclerView rvPosts;
    private PostAdapter postAdapter;
    private List<Post> postList;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Log.d(TAG, "onCreateView: 创建DiscoveryFragment视图");
        View view = inflater.inflate(R.layout.fragment_discovery, container, false);
        Log.d(TAG, "onCreateView: 布局已加载");
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Log.d(TAG, "onViewCreated: 初始化DiscoveryFragment视图组件");
        
        handler = new Handler(Looper.getMainLooper());
        
        try {
            // 初始化轮播图
            bannerViewPager = view.findViewById(R.id.viewpager_banners);
            indicatorContainer = view.findViewById(R.id.indicator_container);
            
            // 设置轮播图适配器
            setupBannerViewPager();
            
            // 初始化 RecyclerView
            rvPosts = view.findViewById(R.id.rv_posts);
            rvPosts.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
            
            // 初始化数据
            postList = new ArrayList<>();
            // 添加测试数据
            postList.add(new Post("中医养生小贴士", "春夏养阳，秋冬养阴", "用户名", 138, R.drawable.tcm_health));
            postList.add(new Post("艾灸养生", "艾灸可以温通经络，祛寒除湿", "养生专家", 256, R.drawable.moxibustion));
            postList.add(new Post("穴位按摩", "每天按摩三个穴位，气血更通畅", "健康顾问", 189, R.drawable.acupoint_massage));
            postList.add(new Post("四季养生", "立春养肝，立夏养心，立秋养肺，立冬养肾", "养生大师", 320, R.drawable.seasonal_health));
            
            // 设置适配器
            postAdapter = new PostAdapter(postList);
            rvPosts.setAdapter(postAdapter);
            // 新增：点击事件，跳转详情
            postAdapter.setOnItemClickListener((post, position) -> {
                Intent intent = new Intent(getContext(), com.simon.jkxj.ui.home.PostDetailActivity.class);
                intent.putExtra("title", post.getTitle());
                intent.putExtra("imageResId", post.getImageResourceId());
                // 随机生成内容
                String[] randomContents = {
                    "健康生活，从每天一杯温水开始。坚持锻炼，保持好心情。",
                    "中医讲究顺应四时，春养肝、夏养心、秋养肺、冬养肾。",
                    "艾灸有助于调理气血，改善体质。",
                    "合理膳食，荤素搭配，营养均衡。",
                    "每天按摩三大穴位，助力身体健康。"
                };
                String detail = randomContents[new Random().nextInt(randomContents.length)];
                intent.putExtra("detail", detail);
                getContext().startActivity(intent);
            });
            
            Log.d(TAG, "onViewCreated: 所有视图组件初始化完成");
        } catch (Exception e) {
            Log.e(TAG, "onViewCreated: 初始化视图组件时出错", e);
        }
    }
    
    private void setupBannerViewPager() {
        // 创建轮播图适配器
        BannerAdapter bannerAdapter = new BannerAdapter();
        bannerViewPager.setAdapter(bannerAdapter);
        
        // 创建指示器
        createBannerIndicators();
        
        // 设置页面切换监听
        bannerViewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                currentBannerPosition = position;
                updateIndicators(position);
            }
        });
        
        // 启动自动滚动
        startBannerAutoScroll();
    }
    
    private void createBannerIndicators() {
        indicatorContainer.removeAllViews();
        
        // 创建指示器圆点
        for (int i = 0; i < BANNER_COUNT; i++) {
            View indicator = new View(requireContext());
            int size = (int) getResources().getDimension(R.dimen.indicator_size);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(size, size);
            params.setMargins(8, 0, 8, 0);
            indicator.setLayoutParams(params);
            indicator.setBackgroundResource(R.drawable.indicator_dot); // 使用圆点指示器样式
            
            // 设置初始状态
            indicator.setSelected(i == 0);
            
            indicatorContainer.addView(indicator);
        }
    }
    
    private void updateIndicators(int position) {
        for (int i = 0; i < indicatorContainer.getChildCount(); i++) {
            View indicator = indicatorContainer.getChildAt(i);
            indicator.setSelected(i == position % BANNER_COUNT);
        }
    }
    
    private void startBannerAutoScroll() {
        if (bannerTimer != null) {
            bannerTimer.cancel();
        }
        
        bannerTimer = new Timer();
        bannerTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                handler.post(() -> {
                    currentBannerPosition = (currentBannerPosition + 1) % BANNER_COUNT;
                    bannerViewPager.setCurrentItem(currentBannerPosition, true);
                });
            }
        }, 3000, 3000); // 3秒切换一次
    }
    
    // 轮播图适配器
    private class BannerAdapter extends androidx.recyclerview.widget.RecyclerView.Adapter<BannerAdapter.BannerViewHolder> {
        
        @NonNull
        @Override
        public BannerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            ImageView imageView = new ImageView(parent.getContext());
            imageView.setLayoutParams(new ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT
            ));
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            return new BannerViewHolder(imageView);
        }
        
        @Override
        public void onBindViewHolder(@NonNull BannerViewHolder holder, int position) {
            // 根据位置设置不同的轮播图图片
            int imageResource;
            switch (position % BANNER_COUNT) {
                case 0:
                    imageResource = R.drawable.index_top;
                    break;
                case 1:
                    imageResource = R.drawable.bannar2;
                    break;
                case 2:
                    imageResource = R.drawable.bannar3;
                    break;
                default:
                    imageResource = R.drawable.index_top;
                    break;
            }
            
            holder.imageView.setImageResource(imageResource);
            holder.imageView.setOnClickListener(v -> {
                Toast.makeText(requireContext(), "点击了轮播图 " + (position + 1), Toast.LENGTH_SHORT).show();
                // TODO: 处理轮播图点击事件
            });
        }
        
        @Override
        public int getItemCount() {
            return BANNER_COUNT;
        }
        
        class BannerViewHolder extends androidx.recyclerview.widget.RecyclerView.ViewHolder {
            ImageView imageView;
            
            public BannerViewHolder(@NonNull View itemView) {
                super(itemView);
                imageView = (ImageView) itemView;
            }
        }
    }
    
    @Override
    public void onResume() {
        super.onResume();
        Log.d(TAG, "onResume: DiscoveryFragment已恢复");
        startBannerAutoScroll();
    }
    
    @Override
    public void onPause() {
        super.onPause();
        if (bannerTimer != null) {
            bannerTimer.cancel();
            bannerTimer = null;
        }
    }
    
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (bannerTimer != null) {
            bannerTimer.cancel();
            bannerTimer = null;
        }
    }
} 